package com.burgeon.backend.college.control_panel.service.Impl;


import com.burgeon.backend.SHOPBACKEND.entity.Marketing;
import com.burgeon.backend.SHOPBACKEND.service.ex.ErrorDataException;
import com.burgeon.backend.SHOPBACKEND.service.ex.UploadException;
import com.burgeon.backend.college.control_panel.entity.*;
import com.burgeon.backend.college.control_panel.mappers.BackendCollegeMapper;
import com.burgeon.backend.college.control_panel.service.BackendCollegeService;
import com.burgeon.backend.college.control_panel.service.util.PDFToImageUtil;
import com.burgeon.backend.college.control_panel.service.util.ReadUtil;
import org.apache.poi.hssf.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.burgeon.backend.SHOP.service.Impl.OrderServiceImpl.getOrderIdByUUId;

@Service
public class BackendCollegeServiceImpl implements BackendCollegeService {

    @Autowired
    private BackendCollegeMapper backendCollegeMapper;
    @Autowired
    private ReadUtil readUtil;


    @Override
    public void exportAchievement(String examId, HttpServletResponse response) {
        List<BExamRecord> examRecord = backendCollegeMapper.findExamRecordByToken(examId);




        String[] headers = {"姓名",
                "学习完成时间",
                "考试结束时间",
                "考试时长",
                "考试成绩",
                "考员请求"};

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        //设置列宽
        sheet.setDefaultColumnWidth((short) 18);
        //创建第一行的对象，第一行一般用于填充标题内容。从第二行开始一般是数据
        HSSFRow row = sheet.createRow(0);

        for (short i = 0; i < headers.length; i++) {
            //创建单元格，每行多少数据就创建多少个单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            //给单元格设置内容
            cell.setCellValue(text);

//            cell=row1.createCell(i);
//            text = new HSSFRichTextString(hm[i]);
//
//            cell.setCellValue(text);

        }
        int ii=1;
        for (BExamRecord bExamRecord :examRecord){
            CourseRecord courseRecord = backendCollegeMapper.findCourseRecordByExamId(bExamRecord.getExam_id(), bExamRecord.getEmp_id());
            if (null != courseRecord) {
                bExamRecord.setCourseTime(courseRecord.getEndTime());
            }
            String[] hm = {bExamRecord.getEmp_name(),
                    bExamRecord.getCourseTime(),
                    bExamRecord.getCreateTime(),
                    bExamRecord.getExamTime(),
                    bExamRecord.getScore()+"",
                    bExamRecord.getApply()

            };

            HSSFRow row1 = sheet.createRow(ii++);


            for (short i = 0; i < hm.length; i++) {
                //创建单元格，每行多少数据就创建多少个单元格
                HSSFCell cell = row1.createCell(i);
                HSSFRichTextString text = new HSSFRichTextString(hm[i]);
                //给单元格设置内容
                cell.setCellValue(text);

//            cell=row1.createCell(i);
//            text = new HSSFRichTextString(hm[i]);
//
//            cell.setCellValue(text);

            }


        }





      //  HSSFRow row1 = sheet.createRow(1);



        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + "Template.xls");//Excel文件名
        try {
            response.flushBuffer();
            //将workbook中的内容写入输出流中
            workbook.write(response.getOutputStream());

        } catch (IOException e) {

            e.printStackTrace();
            throw new ErrorDataException(e.getMessage());
        }

    }

    @Override
    public HashMap uploadCourseware(MultipartFile coursewareFile, String token) throws UploadException {

        if (coursewareFile == null || coursewareFile.isEmpty()) {
            throw new UploadException("文件为空");
        }
        String uuId = getOrderIdByUUId();
        HashMap data = new HashMap();

        String type = "";
        String fileName = coursewareFile.getOriginalFilename(); //文件名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));// 后缀名

//        if (".mp4".equals(suffixName)){
//            type="V";
//        }else if ()
        switch (suffixName) {
            case ".MP4" :
            case ".mp4" :
                type = "VIDEO";
                break;
            case ".PDF":
            case ".pdf":
                type = "PDF";
        }


        if ("PDF".equals(type)) {
            //http://lfwdcdn.cloudsmicro.com/img/mgg-shop/2.png
            String filePath = "//root//code//img//" + token + "-course//pdf//"; // 上传后的路径
            fileName = uuId + suffixName; // 新文件名

            //存入数据库
            //    String pdfURL = "http://lfwdcdn.cloudsmicro.com/img/" + token + "-course/pdf/" + fileName;

            saveFile(coursewareFile, fileName, filePath);


            int count = PDFToImageUtil.PdfToPng(uuId, filePath, fileName);

            for (int i = 0; i < count; i++) {
                backendCollegeMapper.createCourseCourseware(uuId,
                        "http://lfwdcdn.cloudsmicro.com/img/"
                                + token
                                + "-course/pdf/"
                                + uuId
                                + "/" + i + ".png"
                );
            }
            // backendCollegeMapper.upCourseType(course.getId(), "PDF");

        } else if ("VIDEO".equals(type)) {
//            String fileName = coursewareFile.getOriginalFilename(); //文件名
//            String suffixName = fileName.substring(fileName.lastIndexOf("."));// 后缀名
//            //http://lfwdcdn.cloudsmicro.com/img/mgg-shop/2.png
            String filePath = "//root//code//img//" + token + "-course//video//"; // 上传后的路径
            fileName = uuId + suffixName; //新文件名

            //     String videoURL = "http://lfwdcdn.cloudsmicro.com/img/" + token + "-course/video/" + fileName;

            saveFile(coursewareFile, fileName, filePath);
            //  backendCollegeMapper.upCourseVideo(course.getId(), videoURL);
            //  backendCollegeMapper.upCourseType(course.getId(), "VIDEO");
        }else {
            throw new UploadException("文件类型错误 支持.mp4视频文件或.pdf");
        }
        data.put("type",type);
        data.put("code",uuId);
        return data;
    }

    //排序
    @Override
    public void upExamItemSort(String id, Integer num) {

        ExamItem examItem = backendCollegeMapper.getExamItem(id);
        ArrayList<ExamItem> examItemList = backendCollegeMapper.getExamListItem(examItem.getExamId());
        int row = 0;
        for (int i = 0; i < examItemList.size(); i++) {
            examItemList.get(i).setNum(i);
            if (examItemList.get(i).getId().equals(id)) {
                row = i;
            }

        }
        System.err.println(examItemList);
        System.err.println("***************************");
        System.err.println(row + "'" + num);
        int size = examItemList.size();
        int nownum = row + num;

        if (nownum >= 0 && nownum < size) {
            Collections.swap(examItemList, row, row + num);
            System.err.println(examItemList);
        }


        for (int i = 0; i < examItemList.size(); i++) {
            backendCollegeMapper.upExamItemNum(examItemList.get(i).getId(), i);
        }


    }

    @Override
    public void setExam(String id, String course_id, String publisher, String startTime,
                        String endTime, Integer exam_duration) {

        backendCollegeMapper.setExam(id, course_id, publisher, startTime, endTime, exam_duration);
    }

    @Override
    public void consentExam(String id) {

        backendCollegeMapper.upExamRecordApply(id);
    }

    @Override
    public HashMap getExamRecord(String name, String examId, Integer start) {
        HashMap data = new HashMap();

        List<BExamRecord> ExamRecords = backendCollegeMapper.getExamRecord(name, examId, start);
        for (BExamRecord bExamRecord : ExamRecords) {
            CourseRecord courseRecord = backendCollegeMapper.findCourseRecordByExamId(examId, bExamRecord.getEmp_id());
            if (null != courseRecord) {
                bExamRecord.setCourseTime(courseRecord.getEndTime());
            }
        }

        data.put("list", ExamRecords);
        data.put("count", backendCollegeMapper.getExamRecordCount(name, examId));

        return data;
    }

    @Override
    public void delCourse(String id) {
        Exam exam = backendCollegeMapper.getExamByCid(id);
        backendCollegeMapper.delCourse(id);
        if (null != exam)
            delExam(exam.getId());
    }

    @Override
    public void delExam(String id) {
        backendCollegeMapper.delExam(id);
    }

    @Override
    public Exam getExam(String id) {
        Exam exam = backendCollegeMapper.getExam(id);

        class SortByMarketing implements Comparator {
            public int compare(Object o1, Object o2) {
                ExamItem s1 = (ExamItem) o1;
                ExamItem s2 = (ExamItem) o2;

                if (s1.getNum() > s2.getNum()){
                    return 1;
                }

                return -1;
                //不用写s1.getAge()==s2.getAge()的情况
            }

        }
        if (exam != null) {
            for (ExamItem examItem : exam.getExamItems()) {
                examItem.setStrScore(examItem.getScore() + "");//test
            }
            Collections.sort(exam.getExamItems(), new SortByMarketing());
        }



        return exam;
    }

    @Override
    public List<Course> getCourseList(String account) {


        return backendCollegeMapper.getCourseListByOption(account);
    }

    @Override
    public void upExamSwitch(String id, String EW) {

        backendCollegeMapper.upExamSwitch(id, EW);

    }

    @Override
    public void upCourse(MultipartFile imgFile, String code,String type, Course course) throws UploadException {


        if (null != imgFile && !imgFile.isEmpty()) {
            String fileName = imgFile.getOriginalFilename(); //文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));// 后缀名
            //http://lfwdcdn.cloudsmicro.com/img/mgg-shop/2.png
            String filePath = "//root//code//img//" + course.getToken() + "-course//img//"; // 上传后的路径
            fileName = course.getId() + suffixName; // 新文件名

            //存入数据库
            String imgURL = "http://lfwdcdn.cloudsmicro.com/img/" + course.getToken() + "-course/img/" + fileName;
            course.setImg(imgURL);

            saveFile(imgFile, fileName, filePath);
        }

        if ("PDF".equals(type)){
            //更改code为cid
            backendCollegeMapper.upCidByCode(code,course.getId());
            backendCollegeMapper.upCourseType(course.getId(), "PDF");
        }else if ("VIDEO".equals(type)){
            String videoURL = "http://lfwdcdn.cloudsmicro.com/img/" + course.getToken() + "-course/video/" + code+".mp4";
            backendCollegeMapper.upCourseVideo(course.getId(), videoURL);
            backendCollegeMapper.upCourseType(course.getId(), "VIDEO");
        }

       /* if (!pdfFile.isEmpty()) {

            String fileName = pdfFile.getOriginalFilename(); //文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));// 后缀名
            //http://lfwdcdn.cloudsmicro.com/img/mgg-shop/2.png
            String filePath = "//root//code//img//" + course.getToken() + "-course//pdf//"; // 上传后的路径
            fileName = course.getId() + suffixName; // 新文件名

            String pdfURL = "http://lfwdcdn.cloudsmicro.com/img/" + course.getToken() + "-course/pdf/" + fileName;
            course.setCourseware(pdfURL);
            saveFile(pdfFile, fileName, filePath);


            int count = PDFToImageUtil.PdfToPng(course.getId(), filePath, fileName);
            backendCollegeMapper.delCourseCourseware(course.getId());
            for (int i = 0; i < count; i++) {
                backendCollegeMapper.createCourseCourseware(course.getId(),
                        "http://lfwdcdn.cloudsmicro.com/img/"
                                + course.getToken()
                                + "-course/pdf/"
                                + course.getId()
                                + "/" + i + ".png"
                );
            }
            backendCollegeMapper.upCourseType(course.getId(), "PDF");

        } else {
            videoFileSave(video, course);
        }*/

        backendCollegeMapper.upCourse(course);

    }

    private void videoFileSave(MultipartFile video, Course course) {
        if (video != null || !video.isEmpty()) {
            String fileName = video.getOriginalFilename(); //文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));// 后缀名
            //http://lfwdcdn.cloudsmicro.com/img/mgg-shop/2.png
            String filePath = "//root//code//img//" + course.getToken() + "-course//video//"; // 上传后的路径
            fileName = course.getId() + suffixName; // 新文件名

            String videoURL = "http://lfwdcdn.cloudsmicro.com/img/" + course.getToken() + "-course/video/" + fileName;
            course.setVideo(videoURL);
            saveFile(video, fileName, filePath);
            backendCollegeMapper.upCourseVideo(course.getId(), videoURL);
            backendCollegeMapper.upCourseType(course.getId(), "VIDEO");
        }
    }

    @Override
    @Transactional
    public void createCourse(MultipartFile imgFile,String code,String type, Course course) throws Exception {
        if (null == imgFile || imgFile.isEmpty()) {
            System.out.println("封面为空");
            throw new UploadException("封面为空");
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowDate = sdf.format(new Date());
        course.setCreateTime(nowDate);
        Integer newCourseId = backendCollegeMapper.createCourse(course);

        System.err.println(newCourseId.toString());
        //新课程发布通知
        //ewInfoService.sendNewCourseOrExamNotice(course.getToken(),newCourseId.toString(),"KC");

        //储存封面
        {
            String fileName = imgFile.getOriginalFilename(); //文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));// 后缀名
            //http://lfwdcdn.cloudsmicro.com/img/mgg-shop/2.png
            String filePath = "//root//code//img//" + course.getToken() + "-course//img//"; // 上传后的路径
            fileName = course.getId() + suffixName; // 新文件名

            //存入数据库
            String imgURL = "http://lfwdcdn.cloudsmicro.com/img/" + course.getToken() + "-course/img/" + fileName;
            course.setImg(imgURL);
            saveFile(imgFile, fileName, filePath);
        }

        if ("PDF".equals(type)){
            //更改code为cid
            backendCollegeMapper.upCidByCode(code,course.getId());
            backendCollegeMapper.upCourseType(course.getId(), "PDF");
        }else {
            String videoURL = "http://lfwdcdn.cloudsmicro.com/img/" + course.getToken() + "-course/video/" + code+".mp4";
            backendCollegeMapper.upCourseVideo(course.getId(), videoURL);
            backendCollegeMapper.upCourseType(course.getId(), "VIDEO");
        }

        //储存课件

       /* if (pdfFile != null && !pdfFile.isEmpty()) {
            String fileName = pdfFile.getOriginalFilename(); //文件名
            String suffixName = fileName.substring(fileName.lastIndexOf("."));// 后缀名
            //http://lfwdcdn.cloudsmicro.com/img/mgg-shop/2.png
            String filePath = "//root//code//img//" + course.getToken() + "-course//pdf//"; // 上传后的路径
            fileName = course.getId() + suffixName; // 新文件名

            //存入数据库
            String pdfURL = "http://lfwdcdn.cloudsmicro.com/img/" + course.getToken() + "-course/pdf/" + fileName;
            course.setCourseware(pdfURL);
            saveFile(pdfFile, fileName, filePath);


            int count = PDFToImageUtil.PdfToPng(course.getId(), filePath, fileName);

            for (int i = 0; i < count; i++) {
                backendCollegeMapper.createCourseCourseware(course.getId(),
                        "http://lfwdcdn.cloudsmicro.com/img/"
                                + course.getToken()
                                + "-course/pdf/"
                                + course.getId()
                                + "/" + i + ".png"
                );
            }
            backendCollegeMapper.upCourseType(course.getId(), "PDF");

        } else videoFileSave(video, course);
*/

        backendCollegeMapper.upCourseImg(course.getId(), course.getImg());


    }

    @Override
    public HashMap getCourse(String field, String message, String token, int start) {
        HashMap data = new HashMap();
        HashMap<String, String> map = new HashMap<String, String>();
        map.put("A", "title");
        map.put("B", "publisher");
        map.put("C", null);
        List<Course> courseList = backendCollegeMapper.getCourseList(map.get(field), message, token, start);
        for (Course course :courseList){
            Exam exam = backendCollegeMapper.getExamByCid(course.getId());
            course.setIsExam(null==exam?"N":"Y");//N无考试
        }
        int count = backendCollegeMapper.getCourseListCount(map.get(field), message, token, start * 20);
        data.put("courseList", courseList);
        data.put("count", count);

        return data;
    }

    @Override
    @Transactional
    public void uploadingExam(String id, MultipartFile file) throws UploadException {


        if (null == id) {
            throw new UploadException("id为空");
        }
        if (null == file || file.isEmpty()) {
            throw new UploadException("文件为空");
        }
        //删除考题
        List<ExamItem> examListItem = backendCollegeMapper.getExamListItem(id);
        for (ExamItem examItem : examListItem) {
            List<Option> options = backendCollegeMapper.getOption(examItem.getId());
            for (Option option : options) {
                backendCollegeMapper.delOption(option.getId());
            }
            backendCollegeMapper.delExamItem(examItem.getId());
        }

        try {
            List<ExamItem> examItems = readUtil.ReadXls(id, file);

        } catch (IOException e) {
            e.printStackTrace();
            throw new UploadException(e.getMessage());
        }
    }

    @Override
    public void publishExam(String id) throws Exception {
        Integer newExamId = backendCollegeMapper.publishExam(id);
        Exam exam = backendCollegeMapper.getExamById(id);

        //新的考试通知
        //  ewInfoService.sendNewCourseOrExamNotice(exam.getToken(),newExamId.toString(),"KS");

        backendCollegeMapper.upExamSwitch(exam.getCourseId(), "Y");
    }

    @Override
    public void downloadTemplate(HttpServletResponse response) throws ErrorDataException {
        String[] headers = {"题目", "选项A", "选项B", "选项C", "选项D", "答案", "分数"};

        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet sheet = workbook.createSheet();
        //设置列宽
        sheet.setDefaultColumnWidth((short) 18);
        //创建第一行的对象，第一行一般用于填充标题内容。从第二行开始一般是数据
        HSSFRow row = sheet.createRow(0);
        for (short i = 0; i < headers.length; i++) {
            //创建单元格，每行多少数据就创建多少个单元格
            HSSFCell cell = row.createCell(i);
            HSSFRichTextString text = new HSSFRichTextString(headers[i]);
            //给单元格设置内容
            cell.setCellValue(text);
        }

        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=" + "Template.xls");//Excel文件名
        try {
            response.flushBuffer();
            //将workbook中的内容写入输出流中
            workbook.write(response.getOutputStream());

        } catch (IOException e) {

            e.printStackTrace();
            throw new ErrorDataException(e.getMessage());
        }

    }

    @Override
    public void createExamItem(String eid, String title, int score, String result) throws ErrorDataException {
        ExamItem examItem = new ExamItem();
        examItem.setScore(score);
        examItem.setTitle(title);
        examItem.setResult(result);
        examItem.setExamId(eid);

        try {
            backendCollegeMapper.createExamItem(examItem);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ErrorDataException(e.getMessage());
        }
    }

    @Override
    public void createOption(String eiid, String value) {

        Option option = new Option();
        option.setExamItemId(eiid);
        option.setValue(value);
        try {
            backendCollegeMapper.createOption(option);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ErrorDataException(e.getMessage());
        }

    }

    @Override
    public void upExamItem(String id, String title, int score, String result) throws ErrorDataException {
        Integer row = backendCollegeMapper.upExamItem(id, title, score, result);
        if (row != 1) {
            throw new ErrorDataException("系统错误");
        }
    }

    @Override
    public void upOption(String id, String value) throws ErrorDataException {
        System.err.println("&&&&&&&&=="+id+"%%%%%%%%%%"+value);
        Integer row = backendCollegeMapper.upOption(id, value);
        if (row != 1) {
            throw new ErrorDataException("系统错误");
        }
    }

    @Override
    public void delExamItem(String id) throws ErrorDataException {
        Integer row = backendCollegeMapper.delExamItem(id);

    }

    @Override
    public void delOption(String id) throws ErrorDataException {
        Integer row = backendCollegeMapper.delOption(id);
    }

    @Override
    public HashMap getExam(String field, String message, int start, String token) {

        HashMap<String, String> map = new HashMap<String, String>();
        map.put("A", "c.title");
        map.put("B", "e.publisher");
        map.put("C", null);

        HashMap data = new HashMap();

        List<Exam> examList = backendCollegeMapper.getExamList(map.get(field), message, start, token);
        String count = backendCollegeMapper.getExamListCount(map.get(field), message, token);
        for (Exam exam : examList) {
            List<ExamItem> examListItem = backendCollegeMapper.getExamListItem(exam.getId());
            for (ExamItem examItem : examListItem) {
                List<Option> option = backendCollegeMapper.getOption(examItem.getId());
                examItem.setOptions(option);
            }
            exam.setExamItems(examListItem);
        }

        data.put("list", examList);
        data.put("count", count);
        return data;
    }

    @Override
    public HashMap createExam(String id, String publisher,
                              String startTime, String endTime, int examDuration,
                              String token) throws UploadException, ErrorDataException {

        //查询课程id所属考试 不为空抛出异常

        Exam examData = backendCollegeMapper.getExamByCid(id);
        if (examData != null) {
            throw new ErrorDataException("此课程已创建考题,需要删除之后创建");
        }


        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String nowTime = sdf.format(new Date());

        Exam exam = new Exam();
        exam.setCourseId(id);
        exam.setStartTime(startTime);
        exam.setEndTime(endTime);
        exam.setPublisher(publisher);
        exam.setExamDuration(examDuration);
        exam.setToken(token);
        exam.setCreateTime(nowTime);
        backendCollegeMapper.createExam(exam);

//        try {
//            readUtil.ReadXls(exam.getId(),file);
//        } catch (IOException e) {
//            e.printStackTrace();
//            throw new UploadException(e.getMessage());
//        }
        HashMap data = new HashMap();
        data.put("id", exam.getId());

        return data;

    }

    //保存文件
    private void saveFile(MultipartFile multipartFile, String fileName, String filePath) {
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            multipartFile.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
            throw new com.burgeon.backend.service.ex.UploadException("系统错误");
        } catch (Exception e) {
            System.err.println(e.getMessage());
            throw new com.burgeon.backend.service.ex.UploadException("系统错误");
        }
    }
}
